package com.comon.core.utils;

import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * Created with Intellij IDEA.
 * Description;
 * User:TQ02
 * Data:2024-08-24
 * Time:14:47
 * Text：盐值和 MD5 进行密码加密
 */
@Component
public class PasswordUtil {
    public  String encrypt(String password){
        //盐值
        String salt= UUID.randomUUID().toString().replace("-","");
        //盐值+密码
        String finalPassword= DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        return salt+"$"+finalPassword;
    }
    public  boolean decrypt(String password,String dbPassword) {
        if (!StringUtils.hasLength(password) || !StringUtils.hasLength(dbPassword) ||
                dbPassword.length() > 65) {
            return false;
        }
        String[] dppasswordArray = dbPassword.split("\\$");
        if (dppasswordArray.length != 2)
            return false;
        String salt = dppasswordArray[0];
        String dpFinalPassword = dppasswordArray[1];
        String finalPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes(StandardCharsets.UTF_8));
        if (finalPassword.equals(dpFinalPassword)) {
            return true;
        }
        return false;
    }
}
